import styles from './index.less';
import { Input, Typography } from 'antd';
import { useState } from 'react';
import { useDeepCompareEffect } from 'ahooks';

const { Text } = Typography;

const CommonSpecs = (props: any) => {
  const { value, onChange, showType } = props;
  const [addPrice, setAddPrice] = useState<any>(0);
  const [attr, setAttr] = useState<any>();
  const [remark, setRemark] = useState<any>(0);

  const triggerChange = (changedValue: { addPrice?: number; attr?: string; remark?: string }) => {
    onChange?.({ addPrice, attr, remark, ...value, ...changedValue });
  };

  // 改变规格名称
  const attrChange = (e: { target: { value: any } }) => {
    setAttr(e.target.value);
    triggerChange({ attr: e.target.value });
  };

  // 改变规格备注
  const remarkChange = (e: { target: { value: any } }) => {
    setRemark(e.target.value);
    triggerChange({ remark: e.target.value });
  };

  // 改变加价金额
  const fullChange = (e: { target: { value: any } }) => {
    let val = parseFloat(e.target.value || '0');
    if (val < 0) {
      val = 0;
    }
    setAddPrice(val);
    triggerChange({ addPrice: val });
  };

  useDeepCompareEffect(() => {
    setAttr(value?.attr);
    setRemark(value?.remark);
    setAddPrice(value?.addPrice || 0);
  }, [value]);

  return (
    <div>
      <div className={styles.specsInput}>
        <Input
          placeholder="填写规格"
          className={styles.firstInput}
          value={attr}
          onChange={attrChange}
        />
        <Input placeholder="备注（如80%选择）非必填" value={remark} onChange={remarkChange} />
      </div>
      {showType === '1' && (
        <div className={styles.rowView}>
          <div className={styles.disCountView}>
            <div className={styles.innerTextView}>
              <Text type="secondary" style={{ marginLeft: '10px' }}>
                加价
              </Text>
            </div>
            <Input
              className={styles.userInput}
              type={'number'}
              bordered={false}
              value={addPrice}
              onChange={fullChange}
            />
            <div className={styles.innerRightTextView}>
              <Text type="secondary">元</Text>
            </div>
          </div>
          <div className={styles.lastTextView}>
            <Text type="secondary">非必填</Text>
          </div>
        </div>
      )}
    </div>
  );
};
export default CommonSpecs;
